<template>
  <div class="icoPage">
    <div class="icoHead flex justify-between py-20">
        <div class="iconBack ml-16">
          <van-icon name="arrow-left" size="24" color="#fff" @click="$router.replace('/home')"/>
        </div>
        <div class="headTabs flex">
          <div class="headTabsItem" :class="tabActive ? 'active' : '' " @click="changeTab('buy')">
            <span>{{$t('申购')}}</span>
          </div>
          <div class="headTabsItem" :class="tabActive ? '' : 'active' " @click="changeTab('search')">
            <span>{{$t('查询')}}</span>
          </div>
        </div>
        <div></div>
    </div>
<!--    ico申购列表-->
    <div class="icoLists" v-if="tabActive">
      <div class="icoListTab ">
        <div class="icoListType flex ml-32 items-center">
          <div class="icoListTypeItem mr-24" :class="icoListType=== 0 ? 'icoListActive' : '' " @click="changIcoType(0)">
            <span>{{$t('可申购')}}</span>
          </div>
          <div class="icoListTypeItem" :class="icoListType=== 1 ? 'icoListActive' : '' " @click="changIcoType(1)">
            <span>{{$t('待申购')}}</span>
          </div>
        </div>
      </div>

      <div class="buyList">
        <van-list v-model="buySellLoading" :loading-text="$t('加载中...')" :finished="buySellFinished" :immediate-check="false"
                  :finished-text="icoList.length ? $t('已经全部加载完毕') : ''" @load="getIcoList(icoListType === 0)"
                  offset="130" class="px-16">
        <div class="buyListBox" v-if="icoList.length>0">
          <div class="icoListItem" v-for="item in icoList" :key="item.id" @click="showPopup(item)">
            <div class="top flex items-center justify-between">
              <div class="font-44 font-600 text-white">{{item.name}}</div>
              <div>
                <div class="topTime">
                  <span>{{$t('申购')}}</span>
                  <span>{{item.apply_time}}</span>
                </div>
                <div class="topTime">
                  <span>{{$t('上市')}}</span>
                  <span>{{item.sell_time}}</span>
                </div>
              </div>
            </div>
            <div class="mid flex justify-between items-center py-30">
              <div class="midItem">
                <div class="title">{{$t('剩余数量')}}</div>
                <div class="num">{{item.remain_amount}}</div>
              </div>
              <div class="midItem text-center">
                <div class="title">{{$t('发行数量')}}</div>
                <div class="num">{{item.amount_limit}}</div>
              </div>
              <div class="midItem">
                <div class="title">{{$t('发行价格')}}</div>
                <div class="num">
                  <span>{{item.price}}</span>
                  <span class="font-24"> USDT</span>
                </div>
              </div>
            </div>
            <div class="bottom pb-20" v-if="icoListType===0">
              <div class="mb-20">
                <span class="text-white font-26">{{$t('剩余额度')}}</span>
                <span class="font-26 ml-16" style="color: rgb(49, 181, 115);">{{copPercent(item.remain_amount,item.amount_limit)}}%</span>
              </div>
              <van-progress :percentage="copPercent(item.remain_amount,item.amount_limit)" color="rgb(49, 181, 115)" :show-pivot="false" />
            </div>
          </div>
        </div>
        <div  class="flex flex-col justify-center items-center pt-185"  v-else>
          <div>
            <img src="@/assets/image/assets-center/no-data.png" alt="no-date" class="w-120 h-120" />
            <p class="text-white text-center">{{ $t('暂无数据') }}</p>
          </div>
        </div>
        </van-list>
      </div>
    </div>

<!--    ico查询-->
    <div class="icoInquire" v-else>
      <van-list v-model="icoUserLoading" :loading-text="$t('加载中...')" :finished="icoUserFinished" :immediate-check="false"
                :finished-text="icoUserList.length ? $t('已经全部加载完毕') : ''" @load="getIcoUserOrder"
                offset="130" class="px-16">
        <div class="icoInquireBox" v-if="icoUserList.length>0">
          <div class="icoInquireItem" v-for="item in icoUserList" :key="item.id">
            <div class="top">
              <div class="flex items-center justify-between">
                <div>
                  <p class="font-44 font-600">{{item.product_name}}</p>
                </div>
                <div class="ico-status" :class="item.state === '0' ? '': 'actColor'">
                  {{item.state ==="0" ? $t('未开始') : item.state ==="1" ? $t('已中签') : $t('未中签')}}
                </div>
              </div>
              <div>
                <p class="font-24">{{$t('申购日期')}} {{item.create_time}}</p>
              </div>
            </div>
            <div class="mid flex justify-between items-start py-30">
              <div class="midItem">
                <div class="title">{{$t('申购数量')}}</div>
                <div class="num">{{item.amount}}</div>
              </div>
              <div class="midItem text-center">
                <div class="title">{{$t('发行价格')}}</div>
                <div class="num">{{item.order_unit_price}}</div>
              </div>
              <div class="midItem text-right">
                <div class="title">{{$t('上市日期')}}</div>
                <div class="num">
                  <span>{{item.product_sell_time}}</span>
                </div>
              </div>
            </div>
            <div class="bottom pb-20 font-32">
              <span class="font-28 mr-16">{{$t('总额')}}</span>
              <span class="mr-16">{{item.totle_price}}</span>
              <span>USDT</span>
            </div>
          </div>
        </div>
        <div  class="flex flex-col justify-center items-center pt-185"  v-else>
          <div>
            <img src="@/assets/image/assets-center/no-data.png" alt="no-date" class="w-120 h-120" />
            <p class="text-white text-center">{{ $t('暂无数据') }}</p>
          </div>
        </div>
      </van-list>

    </div>

<!--    新币申购弹窗-->
    <van-popup class="w-748" v-model="isShow" round>
      <div class="py-30 px-40">
        <div class="font-40 mb-40">{{$t('新币申购')}}</div>
        <div class="icoDetail flex justify-between items-center">
          <div class="font-32">{{popupData.name}}</div>
          <div class="">
            <div>
              <span class="font-60">{{popupData.price}}</span>
              <span class="font-24"> USDT</span>
            </div>
            <div class="font-24 mb-20">{{$t('发行价格')}}</div>
          </div>
        </div>
        <div class="font-26 mb-40 mt-16">
          <span>{{$t('上市日期')}}</span>
          <span>{{popupData.sell_time}}</span>
        </div>
        <div class="flex justify-between">
          <div class="font-28">{{$t('请输入申购数量')}}</div>
          <div class="font-26">
            <span class="mr-16">{{$t('可购数量额度')}}</span>
            <span>{{popupData.remain_amount}}</span>
          </div>
        </div>
        <div class="inputBox">
          <div>
            <input v-model="amount" :placeholder="$t('申购数量')" class="w-full h-90 border-none text-left rounded-lg" style="text-indent: 16px;background-color: #F5F5F5" type="number" />
          </div>
          <div class="text-grey font-26 mt-16 mb-20">
            <span>{{$t('可用金额')}}</span>
            <span class="pl-8 font-600">{{userInfo.balance}}</span>
            <span>USDT</span>
          </div>
          <div>
            <span class="font-26">{{ $t('总额') }}</span>
            <span class="colorMain px-16 font-48">{{ $bigDecimal.round($bigDecimal.multiply(popupData.price,amount),2)}}</span>
            <span class="colorMain font-26">USDT</span>
          </div>
        </div>
        <div class="btnMain w-full rounded-lg text-center h-100 lh-100 text-white mt-30" @click="throttleFn">
          <span>{{$t('申购')}}</span>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》 ';
import {Progress, Popup, List} from 'vant';
import {_getBalance} from "@/API/trade.api";
import { mapGetters } from 'vuex';
import { throttle } from '@/utils/utis'
import {_getIcoList, _getIcoDetails, _icoApplyOrder, _icoUserOrder, _icoUserOrderDetails} from "@/API/ico";
export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {
    [Progress.name]:Progress,
    [Popup.name]:Popup,
    [List.name]: List,

  },
  props: {},
  data() {
    // 这里存放数据
    return {
      tabActive:true,
      icoListType:0,//0 可申购，1 待申购
      icoList:[],
      isShow:false,
      popupData:{},
      amount:undefined,
      session_token:'',
      page: 1,
      buySellLoading: true, // 当loading为true时，不会加载onload
      buySellFinished: false,  // 数据是否请求结束，结束会先显示'已经全部加载完毕'
      noData: false,// 如果没有数据，显示暂无数据
      icoUserList:[],
      icoUserLoading:false, //当loading为true时，转圈圈
      icoUserFinished: false,  // 数据是否请求结束，结束会先显示'已经全部加载完毕'
    }
  },
  // 计算属性 类似于 data 概念
  computed: {
    ...mapGetters('user', ['userInfo']),

  },
  // 监控 data 中的数据变化
  watch: {},
  // 方法集合
  methods: {
    initData(){
      this.icoList = []
      this.icoUserList = []
      this.page = 1
      this.icoUserLoading = true
      this.buySellLoading = true
      this.icoUserFinished = false
      this.buySellFinished = false
    },
    //用户ico 列表
    getIcoUserOrder(){
      if(this.userInfo.token){
        _icoUserOrder({
          page_no:this.page
        }).then(res=>{
          this.icoUserList = [...this.icoUserList, ...res.data]
          // console.log(logs)
          this.icoUserLoading = false
          if (res.data.length < 10) {
            this.icoUserFinished = true
          } else {
            this.page++
          }
        })
      }
    },
    //剩余ico 百分比计算
    copPercent(num1,num2){
      let tempNum = this.$bigDecimal.divide(num1,num2)
      tempNum = tempNum *100
      return this.$bigDecimal.round(tempNum,2)
    },
    //获取ICO列表
    getIcoList(){
      _getIcoList({
        page_no:this.page,
        pageSize:10,
        today_flag:this.icoListType === 0
      }).then(res=>{
        this.icoList = [...this.icoList, ...res.data]
        this.buySellLoading = false
        if (res.data.length < 10) {
          this.buySellFinished = true
        } else {
          this.page++
        }
      })
    },
    //节流下单
    throttleFn: throttle(function (type) {
      this.applyOrdel()
    }, 500),

    applyOrdel(){
      if(this.userInfo.token){
        _icoApplyOrder({
          session_token: this.session_token,
          amount: this.amount,
          ico_product_id: this.popupData.id
        }).then(res=>{
          this.$toast(this.$t('购买成功'))
          this.isShow = false
          this.icoList = []
          this.icoUserList = []
          this.page = 1
          this.getIcoUserOrder()
          this.updataBalance()
          this.tabActive = !this.tabActive
        })
      }else{
        this.$toast(this.$t('请先登录'))
        this.$router.replace('/login')
      }
    },
    // ico列表 用户列表Tab
    changeTab(type){
      this.initData()
      if(type === 'buy'){
        this.getIcoList()
      }else{
        this.getIcoUserOrder()
      }
      this.tabActive = !this.tabActive
    },
    //可申购 待申购
    changIcoType(type){
      this.icoListType = type
      this.initData()
      this.getIcoList()
    },

    showPopup(data){
      if(this.icoListType === 1){
        return
      }
      _getIcoDetails({
        id:data.id,
      }).then(res=>{
        this.popupData = res.data.product
        this.session_token = res.data.session_token // 下单新币需要传这个
      })
      this.amount = undefined
      this.isShow = true
    },
    updataBalance(){
      _getBalance().then((data) => {
        // 刷新余额
        this.$store.commit("user/SET_USERINFO", { balance: data.money });
      });
    }
  },
  // 生命周期 - 创建完成（可以访问当前this 实例）
  created() {
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.getIcoList()
  },
  beforeCreate() {
  },
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  } // 如果页面有 keep-alive 缓存功能,这个函数会触发
}
</script>

<style scoped lang="scss">
.icoPage{
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  background-color: #080726;
  ::v-deep .van-popup {
    background-color: #ffffff;
  }
}
.icoHead{
  background: #0c0a3c;

  .headTabs{
    div:first-child{
      border-radius: 33px 0 0 33px;
    }
    div:last-child{
      border-radius: 0 33px 33px 0;
    }
    .headTabsItem{
      color: #999;
      height: 66px;
      line-height: 66px;
      font-size: 28px;
      padding: 0 35px;
    }
    .active{
      color: #fff;
      background: #007aff;
      font-size: 32px;
    }
  }
}
.icoListTab{
  background: url("@/assets/image/ico/icoHeadBg.jpg");
  background-size: 100% 310px;
  padding: 220px 0 20px;

  .icoListTypeItem{
    color: #636695;
    font-size: 26px;
    min-width: 200px;
    text-align: center;
  }
  .icoListActive{
    color: #fff;
    font-size: 32px;
    border-bottom: 2px solid #fff;
    padding-bottom: 8px;
  }
}

.buyList{
  margin-top: 20px;
  padding: 0 20px;
  .icoListItem{
    margin-bottom: 20px;
    background-color: #110e45;
    border-radius: 10px;
    padding: 20px;
    .topTime{
      font-size: 26px;
      color: #9093c4;
    }
    .midItem{
      .title{
        font-size: 24px;
        color: #636695;
      }
      .num{
        font-size: 32px;
        color: #fff;
        margin-top: 10px;
      }
    }
  }
}
.icoDetail{
  background-color: #110e45;
  padding: 16px 32px;
  border-radius: 16px;
  color: #fff;
}
.inputBox{
  padding: 20px 30px 40px;
}
.icoInquire{
  margin-top: 20px;
  padding: 0 10px;
  color: #fff;
  .icoInquireBox{
    .icoInquireItem{
      margin-bottom: 20px;
      background-color: #110e45;
      padding: 20px;
      border-radius: 20px;
      .top{
        .ico-status{
          color: #999999;
          background-color: #fff;
          font-size: 26px;
          border-radius: 20px;
          padding: 0 12px;
        }
      }
      .mid{
        .midItem{
          flex:1;
          max-width: 32%;
          word-break: break-word;
          .title{
            color: #636695;
            font-size: 24px;
            margin: 10px 0;
          }
        }
        .num{
          font-size: 32px;
        }
      }
      .bottom{
        border-top: 2px solid #080726;
        padding: 20px 0 10px;
      }
    }
  }
}
.actColor{
  color: #F6465D !important;
}
</style>